import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Thread} from '../models/Thread';
import {MessageService} from './message.service';
import 'rxjs/add/operator/map';
import {Message} from '../models/Message';


@Injectable()
export class ThreadService {
  threads: Observable<{ [key: string]: Thread }>;

  constructor(private messageService: MessageService) {
    this.threads = this.messageService.messages
      .map((messages: Message[]) => {
        const threads: { [key: string]: Thread } = {};
        messages.map((message: Message) => {
          threads[message.thread.id] = threads[message.thread.id] || message.thread;
          const messagesThread = threads[message.thread.id];
          if (!messagesThread.lastMessage || messagesThread.lastMessage.sentAt < message.sentAt) {
            messagesThread.lastMessage = message;
          }
        });
        return threads;
      });
  }

}
